package com.hzsparrow.ai.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hzsparrow.ai.entity.Document;
import com.hzsparrow.ai.entity.KnowledgeBase;
import com.hzsparrow.ai.entity.User;
import com.hzsparrow.ai.service.DocumentService;
import com.hzsparrow.ai.service.KnowledgeBaseService;
import com.hzsparrow.ai.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 文档管理控制器
 */
@RestController
@RequestMapping("/api/document")
public class DocumentController {

    @Autowired
    private DocumentService documentService;

    @Autowired
    private KnowledgeBaseService knowledgeBaseService;

    @Autowired
    private UserService userService;

    /**
     * 添加文档
     */
    @PostMapping("/add")
    public ResponseEntity<?> addDocument(@RequestBody Document document) {
        try {
            // 获取当前用户
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            User user = userService.getUserByUsername(authentication.getName());
            
            // 验证知识库
            KnowledgeBase knowledgeBase = knowledgeBaseService.getKnowledgeBase(document.getKnowledgeBaseId());
            if (knowledgeBase == null) {
                return ResponseEntity.badRequest().body("知识库不存在");
            }
            
            // 验证权限
            if (!knowledgeBase.getCreateUserId().equals(user.getId()) && !user.getRole().equals("ROLE_ADMIN")) {
                return ResponseEntity.status(403).body("无权向此知识库添加文档");
            }
            
            // 创建文档
            document.setCreatedBy(user.getId());
            Document savedDocument = documentService.saveDocument(document);
            
            return ResponseEntity.ok(savedDocument);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("添加文档失败: " + e.getMessage());
        }
    }
    
    /**
     * 根据文件信息创建文档
     */
    @PostMapping("/create-from-file")
    public ResponseEntity<?> createDocumentFromFile(@RequestBody Map<String, Object> request) {
        try {
            // 获取当前用户
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            User user = userService.getUserByUsername(authentication.getName());
            
            // 提取参数
            Map<String, Object> fileInfo = (Map<String, Object>) request.get("fileInfo");
            Long knowledgeBaseId = Long.valueOf(request.get("knowledgeBaseId").toString());
            
            // 验证知识库
            KnowledgeBase knowledgeBase = knowledgeBaseService.getKnowledgeBase(knowledgeBaseId);
            if (knowledgeBase == null) {
                return ResponseEntity.badRequest().body("知识库不存在");
            }
            
            // 验证权限
            if (!knowledgeBase.getCreateUserId().equals(user.getId()) && !user.getRole().equals("ROLE_ADMIN")) {
                return ResponseEntity.status(403).body("无权向此知识库添加文档");
            }
            
            // 创建文档
            Document savedDocument = documentService.createDocumentFromFile(fileInfo, knowledgeBaseId, user.getId());
            
            return ResponseEntity.ok(savedDocument);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("创建文档失败: " + e.getMessage());
        }
    }

    /**
     * 获取知识库下的所有文档
     */
    @GetMapping("/list/{knowledgeBaseId}")
    public ResponseEntity<?> getDocumentsByKnowledgeBase(@PathVariable Long knowledgeBaseId) {
        try {
            // 获取当前用户
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            User user = userService.getUserByUsername(authentication.getName());
            
            // 验证知识库
            KnowledgeBase knowledgeBase = knowledgeBaseService.getKnowledgeBase(knowledgeBaseId);
            if (knowledgeBase == null) {
                return ResponseEntity.badRequest().body("知识库不存在");
            }
            
            // 验证权限
            if (!knowledgeBase.getCreateUserId().equals(user.getId()) && !user.getRole().equals("ROLE_ADMIN")) {
                return ResponseEntity.status(403).body("无权查看此知识库的文档");
            }
            
            List<Document> documents = documentService.getDocumentsByKnowledgeBaseId(knowledgeBaseId);
            return ResponseEntity.ok(documents);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("获取文档列表失败: " + e.getMessage());
        }
    }

    /**
     * 获取文档详情
     */
    @GetMapping("/{id}")
    public ResponseEntity<?> getDocument(@PathVariable Long id) {
        try {
            // 获取当前用户
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            User user = userService.getUserByUsername(authentication.getName());
            
            // 获取文档
            Document document = documentService.getDocumentById(id);
            if (document == null) {
                return ResponseEntity.badRequest().body("文档不存在");
            }
            
            // 获取知识库
            KnowledgeBase knowledgeBase = knowledgeBaseService.getKnowledgeBase(document.getKnowledgeBaseId());
            
            // 验证权限
            if (!knowledgeBase.getCreateUserId().equals(user.getId()) && !user.getRole().equals("ROLE_ADMIN")) {
                return ResponseEntity.status(403).body("无权查看此文档");
            }
            
            return ResponseEntity.ok(document);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("获取文档详情失败: " + e.getMessage());
        }
    }

    /**
     * 更新文档
     */
    @PutMapping("/{id}")
    public ResponseEntity<?> updateDocument(@PathVariable Long id, @RequestBody Document document) {
        try {
            // 获取当前用户
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            User user = userService.getUserByUsername(authentication.getName());
            
            // 获取现有文档
            Document existingDocument = documentService.getDocumentById(id);
            if (existingDocument == null) {
                return ResponseEntity.badRequest().body("文档不存在");
            }
            
            // 获取知识库
            KnowledgeBase knowledgeBase = knowledgeBaseService.getKnowledgeBase(existingDocument.getKnowledgeBaseId());
            
            // 验证权限
            if (!knowledgeBase.getCreateUserId().equals(user.getId()) && !user.getRole().equals("ROLE_ADMIN")) {
                return ResponseEntity.status(403).body("无权修改此文档");
            }
            
            // 更新文档
            document.setId(id);
            document.setKnowledgeBaseId(existingDocument.getKnowledgeBaseId());
            document.setCreatedBy(existingDocument.getCreatedBy());
            
            Document updatedDocument = documentService.updateDocument(document);
            return ResponseEntity.ok(updatedDocument);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("更新文档失败: " + e.getMessage());
        }
    }

    /**
     * 删除文档
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<?> deleteDocument(@PathVariable Long id) {
        try {
            // 获取当前用户
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            User user = userService.getUserByUsername(authentication.getName());
            
            // 获取文档
            Document document = documentService.getDocumentById(id);
            if (document == null) {
                return ResponseEntity.badRequest().body("文档不存在");
            }
            
            // 获取知识库
            KnowledgeBase knowledgeBase = knowledgeBaseService.getKnowledgeBase(document.getKnowledgeBaseId());
            
            // 验证权限
            if (!knowledgeBase.getCreateUserId().equals(user.getId()) && !user.getRole().equals("ROLE_ADMIN")) {
                return ResponseEntity.status(403).body("无权删除此文档");
            }
            
            boolean result = documentService.deleteDocument(id);
            
            if (result) {
                return ResponseEntity.ok(Map.of("message", "文档删除成功"));
            } else {
                return ResponseEntity.badRequest().body("文档删除失败");
            }
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("删除文档失败: " + e.getMessage());
        }
    }

    /**
     * 获取文档列表
     */
    @GetMapping
    public ResponseEntity<?> listDocuments(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) Long knowledgeBaseId) {
        
        try {
            if (knowledgeBaseId != null) {
                // 检查知识库是否存在
                KnowledgeBase knowledgeBase = knowledgeBaseService.getKnowledgeBase(knowledgeBaseId);
                if (knowledgeBase == null) {
                    return ResponseEntity.badRequest().body("知识库不存在");
                }
            }
            
            Page<com.hzsparrow.ai.entity.Document> result = documentService.listDocuments(page, size, knowledgeBaseId);
            
            Map<String, Object> response = new HashMap<>();
            response.put("total", result.getTotal());
            response.put("pages", result.getPages());
            response.put("current", result.getCurrent());
            response.put("size", result.getSize());
            response.put("records", result.getRecords());
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("Error: " + e.getMessage());
        }
    }

    /**
     * 按知识库ID获取文档列表
     */
    @GetMapping("/list")
    public ResponseEntity<?> getDocumentsByKnowledgeBaseId(@RequestParam Long knowledgeBaseId) {
        try {
            // 获取当前用户
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            User user = userService.getUserByUsername(authentication.getName());
            
            // 验证知识库
            KnowledgeBase knowledgeBase = knowledgeBaseService.getKnowledgeBase(knowledgeBaseId);
            if (knowledgeBase == null) {
                return ResponseEntity.badRequest().body("知识库不存在");
            }
            
            // 验证权限
            if (!knowledgeBase.getCreateUserId().equals(user.getId()) && !user.getRole().equals("ROLE_ADMIN")) {
                return ResponseEntity.status(403).body("无权查看此知识库的文档");
            }
            
            List<Document> documents = documentService.getDocumentsByKnowledgeBaseId(knowledgeBaseId);
            return ResponseEntity.ok(documents);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("获取文档列表失败: " + e.getMessage());
        }
    }
} 